import fs from 'fs';
import path from 'path';
import fsExtra from 'fs-extra';
import axios from 'axios';
import compressing from 'compressing';
import request from 'request';

export function repoPackageExist(repo) {
  return fs.existsSync(path.join(this.$globalConst.reposPath, repo.repoName, 'package', repo.distFolder));
}

export function getRepoNewVersion(repo) {
  return axios({
    method: 'get',
    url: `http://registry.npm.taobao.org/${repo.repoName}/latest`,
    responseType: 'json'
  })
  .then((response) => {
    return response.data.version;
  });
}

export function downloadRepo(repo) {
  return new Promise((resolve) => {
    const tgzPath = path.join(this.$globalConst.reposPath, repo.repoName, '.taz');
    fsExtra.ensureFileSync(tgzPath);
    request(`http://registry.npm.taobao.org/${repo.repoName}/download/${repo.repoName}-${repo.version}.tgz`)
      .pipe(fs.createWriteStream(tgzPath))
      .on('finish', () => {
        resolve();
      });
  });
}

export function uncompressRepo(repo) {
  const tgzPath = path.join(this.$globalConst.reposPath, repo.repoName, '.taz');
  const targetPath = path.join(this.$globalConst.reposPath, repo.repoName);
  return compressing.tgz.uncompress(tgzPath, targetPath);
}

export function getRepoComponentList(repo) {
  return fs.readdirSync(path.join(this.$globalConst.reposPath, repo.repoName, 'package', repo.distFolder));
}

export function emptyRepoPackage(repo) {
  fsExtra.emptyDirSync(path.join(this.$globalConst.reposPath, repo.repoName, 'package', repo.distFolder));
}
